#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# pip install pynput
from pynput import keyboard
from window.keyboard import Keyboard
from window.pid import getAppProcess
from AppKit import NSWorkspace
import Quartz

#
#
kb = Keyboard()
# appname = "wine_tbc276575275Wine"
# appname = "wine_tbc276575275Wine"
appname = "Sublime Text"
appinfo = getAppProcess(appname)
if appinfo is None:
    print "参数异常:未匹配进程"
    exit()
apppid = appinfo['NSApplicationProcessIdentifier']
# psm=Quartz.GetProcessForPID(appinfo)
print '匹配进程:', appinfo
flag = True
# 忽略监听
ignore = ["a", 'w', 's', 'd', keyboard.Key.space]


def check_key(key):
    global ignore
    activeAppName = NSWorkspace.sharedWorkspace().activeApplication()
    if activeAppName.get('NSApplicationName') == appname:
        print "active listen app and ignore"
        return True
    return key in ignore


def on_press(key):
    global flag, appinfo
    try:
        if not check_key(key.char):
            print('普通按键: {0} 按下'.format(key.char))
            if flag:
                # 任意一种发送方式都可以完成
                # kb.KeyPressPid(key.char, True, apppid)
                kb.KeyPressApp(key.char, True, appinfo)
    except AttributeError:
        print key.value
        print('特殊按键: {0} 按下'.format(key))


def on_release(key):
    global flag
    if key == keyboard.Key.f11:
        flag = False if flag else True
        print "listen:", flag
    if key == keyboard.Key.f12:
        # Stop listener
        return False
    try:
        if not check_key(key.char):
            print('普通按键: {0} 弹起'.format(key.char))
            if flag:
                # 任意一种发送方式都可以完成
                # kb.KeyPressPid(key.char, False, apppid)
                kb.KeyPressApp(key.char, False, appinfo)
    except AttributeError:
        print('特殊按键: {0} 弹起'.format(key))


# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    try:
        listener.join()
    except Exception as e:
        print('{0} was pressed'.format(e.args[0]))

# ...or, in a non-blocking fashion:
# listener = keyboard.Listener(
#     on_press=on_press,
#     on_release=on_release)
# listener.start()
